package com.tianji.learning.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tianji.common.exceptions.DbException;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.service.ILearningLessonService;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Yandel
 * @date 2025/5/10 上午9:51
 * @description: 定时检查课程有效期状态
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LessonStatusCheckJob {

    private final ILearningLessonService lessonService;
    @Scheduled(cron = "0 * * * * ?")//每分钟执行一次 域->      秒  分  时  日  月  周  （年）
    public void lessonStatusCheck(){
        //1.查询这状态为未过期的课程         不区分用户
        //Wrappers.<LearningLesson>lambdaQuery() 相当于new QueryWrapper<LearningLesson>()
        //ne表示不等于
        List<LearningLesson> list = lessonService.list(Wrappers.<LearningLesson>lambdaQuery()
                .ne(LearningLesson::getStatus, LessonStatus.EXPIRED));

        //2.判断是否过期   过期时间是不是小于当前时间
        LocalDateTime now = LocalDateTime.now();
        for (LearningLesson lesson : list) {
            if (now.isAfter(lesson.getExpireTime())){//现在时间 大于 过期时间
                lesson.setStatus(LessonStatus.EXPIRED);
            }
        }

        //3.更新
        boolean result = lessonService.updateBatchById(list);
        if (!result){
            throw new DbException("更新课表数据失败");
        }
    }
}
